<!--
 * @Version: 1.0
 * @Autor:
 * @Date: 2021-02-25 17:23:03
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-11-19 18:01:19
 * @Description:
-->
<template>
  <el-card class="app-container content_box" shadow="always">
    <form-selections :is-active="isActive" :items="formItems" :query-param.sync="queryParam" display="block" @handleSearch="handleSearch" />
    <div class="select_flex">
      <div class="operation_button_box">
        <el-button v-action="'shop@save'" size="small" type="success" icon="el-icon-circle-plus" @click="handleCreate()">新增店铺</el-button>
        <el-button v-action="'shop@disable'" :disabled="selectedIds.length?false:true" size="small" type="danger" @click="handleDisable()">禁用</el-button>
        <el-button v-action="'shop@enable'" :disabled="selectedIds.length?false:true" size="small" type="primary" @click="handleEnable()">启用</el-button>
        <el-button v-action="'shop@export'" :disabled="data.length?false:true" size="small" type="primary" @click="formVisibleDown=true">导出</el-button>
      </div>
      <div>
        <el-button size="small" type="primary" class="filter-item search" icon="el-icon-search" @click="handleSearch">
          搜索
        </el-button>
        <el-button size="small" icon="el-icon-refresh" @click="handleRefresh">重置</el-button>
      </div>
    </div>
    <div v-loading="loading">
      <el-table ref="multipleTable" :max-height="screenHeigh" :data="data" tooltip-effect="dark" style="width: 100%" border fit @selection-change="handleSelectMulti">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="操作" align="center" fixed min-width="270px">
          <template slot-scope="scope">
            <span v-if="scope.row.is_status===2" v-action="'shop@update'" class="edit_style" @click="handleUpdateNew(scope.row)">编辑</span>
            <span v-if="scope.row.is_status===2" v-action="'shop@delete'" class="delete_style" @click="handleDelete(scope.row.id)">删除</span>
            <span v-action="'shop@bindWarehouse'" class="edit_style" @click="showBindWarehouseDialog(scope.row.id)">绑定仓库</span>
            <span v-action="'shop@bindUser'" class="edit_style" @click="showBindUserDialog(scope.row.id)">分配人员</span>
            <!-- shop@manualPull -->
            <span v-if="scope.row.is_status===1&&scope.row.platform_id !==3" v-action="'shop@manualPull'" class="edit_style" @click="manualPull(scope.row.id)">拉取订单</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="id" label="店铺ID" />
        <el-table-column align="center" prop="company_name" label="客户名称" width="150px" show-overflow-tooltip />
        <el-table-column align="center" prop="company_id" label="客户ID" />
        <el-table-column align="center" prop="code" label="店铺代码" width="180" />
        <el-table-column align="center" prop="shop_name" label="店铺名称" width="180" show-overflow-tooltip>
          <template slot-scope="scope">
            <code-item :code="scope.row.shop_name" @click="showInfoDialog(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column align="center" prop="is_status" label="状态">
          <template slot-scope="scope">
            {{ scope.row.is_status===1?'启用':'禁用' }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="platform_name" label="归属平台" width="120px" />
        <el-table-column align="center" prop="type" label="运营类型">
          <template slot-scope="scope">
            <!-- 1-自营 2-代储存 -->
            {{ scope.row.type===1?'自营':'代储存' }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="remarks" label="备注" width="150" show-overflow-tooltip>
          <template slot-scope="scope">
            <span style="color:red">{{ scope.row.remarks }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="仓库数量" prop="warehouse_num" />
        <el-table-column align="center" prop="creator_name" label="创建人" width="150" show-overflow-tooltip />
        <el-table-column align="center" prop="created_at" label="创建时间" width="170" />
        <el-table-column align="center" prop="update_name" label="修改人" width="150" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.update_name?scope.row.update_name:'-' }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="updated_at" label="更新时间" width="165" />
      </el-table>
      <el-pagination v-if="paginate.total > 0" class="pagination_box" background :current-page="paginate.current" :page-sizes="[50, 100, 150, 200]" layout="total, sizes, prev, pager, next, jumper" :total="paginate.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
    <!-------- 回到顶部 ------------>
    <el-backtop :visibility-height="60">
      <i class="el-icon-caret-top" />
    </el-backtop>
    <!------------------------------------------------添加店铺-------------------------------------------->
    <el-dialog :center="true" :title="title" :visible.sync="formVisible" width="1200px" @close="handleCancel">
      <el-form :ref="formName" :model="formFieldsData" :rules="rules" inline class="dialog-form-expand" :disabled="isInfo">
        <div class="header_title_box">
          <h2>基本信息</h2>
        </div>
        <el-form-item label="店铺代码" :label-width="formLabelWidth" prop="code">
          <el-input v-model="formFieldsData.code" placeholder="请输入店铺代码" autocomplete="off" clearable oninput="value=value.replace(/[\u4E00-\u9FA5]/g,'')" />
        </el-form-item>
        <el-form-item label="店铺名称" :label-width="formLabelWidth" prop="shop_name">
          <el-input v-model="formFieldsData.shop_name" placeholder="请输入店铺名称" autocomplete="off" clearable />
        </el-form-item>
        <el-form-item label="归属平台" :label-width="formLabelWidth" prop="platform_id">
          <el-select v-model="formFieldsData.platform_id" :disabled="title==='编辑'?true:false" clearable placeholder="请选择归属平台" @change="changePlatform">
            <el-option v-for="(item, index) in platformOptions" :key="index" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <div class="mtb" />
        <el-form-item label="运营类型" :label-width="formLabelWidth" prop="type">
          <!-- 1-自营 2-代储存 -->
          <el-select v-model="formFieldsData.type" clearable placeholder="请选择运营类型">
            <el-option :value="1" label="自营" />
            <el-option :value="2" label="代运营" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户" :label-width="formLabelWidth" prop="company_id">
          <el-select v-model="formFieldsData.company_id" :disabled="title==='编辑'?true:false" filterable remote clearable reserve-keyword placeholder="请输入关键词" :remote-method="remoteMethod" :loading="loadingCompany">
            <el-option v-for="item in optionsCompany" :key="item.value" :disabled="item.is_status===2?true:false" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth" prop="remarks">
          <el-input v-model="formFieldsData.remarks" placeholder="请输入备注" autocomplete="off" clearable />
        </el-form-item>
        <div class="header_title_box">
          <h2>归属平台参数</h2>
        </div>
        <div v-for="item in platformOptionsParam" :key="item.value">
          <div v-if="item.value == formFieldsData.platform_id">
            <span v-for="itemChrild in item.data" :key="itemChrild">
              <el-form-item :label-width="formLabelWidth" :label="itemChrild" :prop="'platformOptionsData.' +itemChrild" :rules="rules[itemChrild]">
                <el-input v-model="formFieldsData.platformOptionsData[itemChrild]" autosize placeholder="请输入" autocomplete="off" clearable @input="inputChange" />
              </el-form-item>
            </span>
          </div>
        </div>
      </el-form>
      <div class="header_title_box">
        <h2 style="margin-right:50px">
          寄件人信息
        </h2>
        <div>
          <el-button type="primary" size="mini" icon="el-icon-plus" @click="addField">新增</el-button>
        </div>
      </div>
      <div>
        <el-form ref="formData" :rules="model.rules" :model="model" class="dialog-form-expand3" :disabled="isInfo">
          <el-table :data="model.fields" tooltip-effect="dark" style="width: 100%" border>
            <el-table-column align="center" label="仓库">
              <template slot-scope="field">
                <el-form-item :prop="'fields.' + field.$index + '.warehouse_name'" :rules="model.rules.warehouse_name">
                  <el-input v-model="field.row.warehouse_name" :disabled="field.row.disabled" placeholder="输入仓库" autocomplete="off" clearable />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" label="寄件人">
              <template slot-scope="field">
                <el-form-item :prop="'fields.' + field.$index + '.name'" :rules="model.rules.name">
                  <el-input v-model="field.row.name" :disabled="field.row.disabled" size="mini" placeholder="输入寄件人姓名" autocomplete="off" clearable />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" label="寄件公司">
              <template slot-scope="field">
                <el-form-item :prop="'fields.' + field.$index + '.company'" :rules="model.rules.company">
                  <el-input v-model="field.row.company" :disabled="field.row.disabled" size="mini" placeholder="输入寄件公司" autocomplete="off" clearable />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" label="手机号码" width="150">
              <template slot-scope="field">
                <el-form-item :prop="'fields.' + field.$index + '.phone'" :rules="model.rules.phone">
                  <el-input v-model="field.row.phone" :disabled="field.row.disabled" size="mini" maxlength="11" placeholder="输入手机号码" autocomplete="off" clearable />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" label="固定座机">
              <template slot-scope="field">
                <el-form-item :prop="'fields.' + field.$index + '.mobile'" :rules="model.rules.mobile">
                  <el-input v-model="field.row.mobile" :disabled="field.row.disabled" size="mini" placeholder="输入固定座机" autocomplete="off" clearable />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" label="街道">
              <template slot-scope="field">
                <el-form-item :prop="'fields.' + field.$index + '.street'" :rules="model.rules.street">
                  <el-input v-model="field.row.street" :disabled="field.row.disabled" size="mini" placeholder="输入街道" autocomplete="off" clearable />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" label="城市">
              <template slot-scope="field">
                <el-form-item :prop="'fields.' + field.$index + '.city'" :rules="model.rules.city">
                  <el-input v-model="field.row.city" :disabled="field.row.disabled" size="mini" placeholder="输入城市" autocomplete="off" clearable />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" label="州/省代码">
              <template slot-scope="field">
                <el-form-item :prop="'fields.' + field.$index + '.city_code'" :rules="model.rules.city_code">
                  <el-input v-model="field.row.city_code" :disabled="field.row.disabled" size="mini" placeholder="输入州/省代码" autocomplete="off" clearable />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" label="邮编">
              <template slot-scope="field">
                <el-form-item :prop="'fields.' + field.$index + '.post_code'" :rules="model.rules.post_code">
                  <el-input v-model="field.row.post_code" :disabled="field.row.disabled" size="mini" placeholder="输入邮编" autocomplete="off" clearable />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" label="是否默认">
              <template slot-scope="field">
                <el-form-item>
                  <el-select v-model="field.row.is_default" size="mini" clearable :disabled="field.row.disabled">
                    <el-option :value="0" label="否" />
                    <el-option :value="1" label="是" />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="150">
              <template slot-scope="field">
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteField(field.row, 'sender')" />
                <el-button v-if="field.row.disabled" type="primary" size="mini" icon="el-icon-edit" @click="editOpen(field.$index)" />
                <el-button v-if="!field.row.disabled && formFieldsData.id" type="primary" size="mini" @click="save(formFieldsData.id, field.row, field.$index, 'sender')">保存</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer-center">
        <template v-if="isInfo">
          <el-button type="primary" @click="handleCancel">返 回</el-button>
        </template>
        <template v-else>
          <el-button @click="handleCancel">取 消</el-button>
          <el-button type="primary" @click="handleSubmitNew">确 定</el-button>
        </template>
      </div>
    </el-dialog>

    <!--下载字段选择-->
    <DownModul url="shops/export" :search-param="queryParam" :form-visible-down.sync="formVisibleDown" titel="店铺导出字段选择" :options-modul="optionsModul" />

    <!-- 绑定仓库 -->
    <bind-warehouse-dialog ref="warehouse" @submit="handleRefresh" />
    <bind-user-dialog ref="user" @submit="handleRefresh" />
    <!-- 拉去订单 -->
    <el-dialog :center="true" title="拉取订单" :visible.sync="formVisiblePull" width="600px" @close="handleCancelPull">
      <el-form ref="handleSubmitPull" :model="formDataPull" :rules="rules1">
        <el-form-item label="选择时间" prop="startTime">
          <el-date-picker v-model="formDataPull.startTime" value-format="yyyy-MM-dd HH:mm:ss" :picker-options="pickerOptions" type="datetime" placeholder="选择日期时间" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer-center">
        <template>
          <el-button @click="handleCancelPull">取 消</el-button>
          <el-button :disabled="loadingPull" :loading="loadingPull" type="primary" @click="handleSubmitPull">确 定</el-button>
        </template>
      </div>
    </el-dialog>
  </el-card>

</template>

<script>
import formOperate from '@/layout/mixin/formOperate'
import { action } from '@/directive/permission/index.js' // 权限判断指令
// import methods from '../../../components/egrid/methods'
import DownModul from '@/components/DownModul/index.vue'
import {
  platformList,
  companyList
} from '@/utils/publicData'
import { validChineseOrs, validateFirstUpperCase } from '@/utils/validate'
import codeItem from '@/components/base/code'
import BindWarehouseDialog from './components/bindWarehouseDialog'
import BindUserDialog from './components/bindUserDialog'
import cacheList from '@/layout/mixin/cacheList'
export default {
  name: 'BasicsShop',
  directives: {
    action
  },
  components: { DownModul, codeItem, BindWarehouseDialog, BindUserDialog },
  mixins: [formOperate, BindUserDialog, cacheList],
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        },
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      loadingPull: false,
      formDataPull: {
        startTime: ''
      },
      shopId: '',
      rules1: {
        startTime: [
          {
            required: true,
            message: '请选择时间',
            trigger: 'blur'
          }
        ]
      },
      formVisiblePull: false,
      otherHeight: 365,
      componentName: 'BasicsShop',
      optionsModul: [
        {
          key: 'id',
          label: 'id'
        },
        {
          key: 'shop_name',
          label: '店铺名称'
        },
        {
          key: 'code',
          label: '编码'
        },
        {
          key: 'is_status',
          label: '状态'
        },
        {
          key: 'type_text',
          label: '运营类型'
        },
        {
          key: 'platform_name',
          label: '所属平台'
        },
        {
          key: 'company_name',
          label: '客户名称'
        },
        {
          key: 'created_at',
          label: '创建时间'
        }
      ],
      formVisibleDown: false,
      id: '',
      loadingdialog: false,
      formVisibleBindWarehouse: false,
      warehouseListData: [],
      unwarehouseListData: [],
      userListData: [],
      unuserListData: [],
      formVisibleBindUser: false,
      platformOptionsData: {},
      platformOptionsParam: [
        {
          value: '2',
          data: [
            'devId',
            'appId',
            'certId',
            'authToken',
            'oauthUserToken',
            'ruName'
          ]
        },
        //   {
        //     value: '1',
        //     data: ['AWSAccessKeyId', 'SecretAccessKey', 'SellerId', 'MWSAuthToken', 'MarketplaceId']
        //   },
        {
          value: '1',
          data: [
            'refreshToken',
            'clientId',
            'clientSecret',
            'accessKey',
            'secretKey',
            'MerchantId',
            'marketplaceId' // ATVPDKIKX0DER
          ]
        },
        {
          value: '3',
          data: ['ftpName', 'ftpPassword', 'host', 'supplierID']
        },
        {
          value: '4',
          data: ['password', 'username']
        },
        {
          value: '5',
          data: ['clientId', 'clientSecretId']
        },
        {
          value: '6',
          data: ['key', 'apiToken', 'username']
        },
        {
          value: '7',
          data: ['apiKey', 'password', 'shopUrl']
        },
        {
          value: '8',
          data: ['appName', 'userName', 'token']
        }
      ],
      formName: 'shops',
      formLabelWidth: '120px',
      loadingCompany: false,
      optionsCompany: [],
      platformOptions: [],
      select: 'code',
      url: '/shop',
      queryParam: {
        status: '',
        code: '',
        name: '',
        type: '',
        limit: 50
      },
      formItems: [
        {
          label: '店铺代码',
          key: 'code',
          type: 'input',
          placeholder: '请输入店铺代码'
        },
        {
          label: '店铺名称',
          key: 'name',
          type: 'input',
          placeholder: '请输入店铺名称'
        },
        {
          label: '客户名称',
          key: 'company_name',
          type: 'input',
          placeholder: '请输入客户名称'
        },
        {
          label: '审核状态',
          key: 'status',
          type: 'select',
          placeholder: '请选择审核状态',
          options: [
            {
              value: 2,
              label: '禁用'
            },
            {
              value: 1,
              label: '启用'
            }
          ]
        },
        {
          label: '平台',
          key: 'platform_id',
          type: 'select',
          placeholder: '请选择平台',
          options: []
        }
      ],
      loading: false,
      formVisible: false,
      formFieldsData: {
        code: '', // 店铺代码
        shop_name: '', // 店铺名称
        platform_id: '', // 归属平台
        type: '', // 运营类型 1-自营 2-代储存
        company_id: '', // 客户id
        remarks: '', // 备注
        platformOptionsData: {}
      },
      // 表单验证
      rules: {
        'platformOptionsData.MerchantId': [
          { required: false, message: '请输入MerchantId', trigger: 'change' }
        ],
        'platformOptionsData.token': [
          { required: false, message: '请输入userName', trigger: 'change' }
        ],
        'platformOptionsData.userName': [
          { required: false, message: '请输入userName', trigger: 'change' }
        ],
        'platformOptionsData.appName': [
          { required: false, message: '请输入appName', trigger: 'change' }
        ],
        'platformOptionsData.marketplaceId': [
          { required: false, message: '请输入marketplaceId', trigger: 'blur' }
        ],
        'platformOptionsData.refreshToken': [
          { required: false, message: '请输入refreshToken', trigger: 'blur' }
        ],
        'platformOptionsData.clientSecret': [
          { required: false, message: '请输入clientSecret', trigger: 'blur' }
        ],
        'platformOptionsData.accessKey': [
          { required: false, message: '请输入accessKey', trigger: 'blur' }
        ],
        'platformOptionsData.secretKey': [
          { required: false, message: '请输入secretKey', trigger: 'blur' }
        ],
        'platformOptionsData.username': [
          { required: false, message: '请输入username', trigger: 'blur' }
        ],
        'platformOptionsData.key': [
          { required: false, message: '请输入key', trigger: 'blur' }
        ],
        'platformOptionsData.apiToken': [
          { required: false, message: '请输入apiToken', trigger: 'blur' }
        ],
        'platformOptionsData.apiKey': [
          { required: false, message: '请输入apiKey', trigger: 'blur' }
        ],
        'platformOptionsData.shopUrl': [
          { required: false, message: '请输入shopUrl', trigger: 'blur' }
        ],
        'platformOptionsData.password': [
          { required: false, message: '请输入password', trigger: 'blur' }
        ],
        'platformOptionsData.supplierID': [
          { required: false, message: '请输入supplierID', trigger: 'blur' }
        ],
        'platformOptionsData.host': [
          { required: false, message: '请输入host', trigger: 'blur' }
        ],
        'platformOptionsData.ftpPassword': [
          { required: false, message: '请输入ftpPassword', trigger: 'blur' }
        ],
        'platformOptionsData.ftpName': [
          { required: false, message: '请输入ftpName', trigger: 'blur' }
        ],
        'platformOptionsData.ruName': [
          { required: false, message: '请输入ruName', trigger: 'blur' }
        ],
        'platformOptionsData.oauthUserToken': [
          { required: false, message: '请输入oauthUserToken', trigger: 'blur' }
        ],
        'platformOptionsData.authToken': [
          { required: false, message: '请输入authToken', trigger: 'blur' }
        ],
        'platformOptionsData.certId': [
          { required: false, message: '请输入certId', trigger: 'blur' }
        ],
        'platformOptionsData.appId': [
          { required: false, message: '请输入appId', trigger: 'blur' }
        ],
        'platformOptionsData.devId': [
          { required: false, message: '请输入devId', trigger: 'blur' }
        ],
        'platformOptionsData.MarketplaceId': [
          { required: false, message: '请输入MarketplaceId', trigger: 'blur' }
        ],
        'platformOptionsData.SellerId': [
          { required: false, message: 'SellerId', trigger: 'blur' }
        ],
        'platformOptionsData.MWSAuthToken': [
          { required: false, message: '请输入MWSAuthToken', trigger: 'blur' }
        ],
        'platformOptionsData.SecretAccessKey': [
          { required: false, message: 'SecretAccessKey', trigger: 'blur' }
        ],
        'platformOptionsData.AWSAccessKeyId': [
          { required: false, message: '请输入AWSAccessKeyId', trigger: 'blur' }
        ],
        'platformOptionsData.clientSecretId': [
          {
            required: false,
            message: '请输入clientSecretId',
            trigger: 'blur'
          }
        ],
        'platformOptionsData.clientId': [
          {
            required: false,
            message: '请输入clientId',
            trigger: 'blur'
          }
        ],
        code: [
          {
            required: true,
            message: '请输入店铺代码',
            trigger: 'blur'
          },
          {
            validator(rule, value, callback) {
              if (validChineseOrs(value)) {
                callback(new Error('代码须是字母，数字，非空字符组成'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        shop_name: [
          {
            required: true,
            message: '请输入店铺名称',
            trigger: 'blur'
          },
          {
            validator(rule, value, callback) {
              if (validateFirstUpperCase(value)) {
                callback(new Error('店铺名称首字母必须大写'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        platform_id: [
          {
            required: true,
            message: '请选择归属平台',
            trigger: 'blur'
          }
        ],
        type: [
          {
            required: true,
            message: '请选择运营类型',
            trigger: 'change'
          }
        ],
        company_id: [
          {
            required: true,
            message: '请选择客户',
            trigger: 'blur'
          }
        ]
      },
      fields: [this.getColumn()],
      model: {
        rules: {
          warehouse_name: {
            required: true,
            message: '必填字段',
            trigger: 'blur'
          },
          phone: [
            { required: true, message: '请输入手机号', trigger: 'blur' },
            { pattern: /^[0-9 -]*$/, message: '请输入正确的手机号', trigger: 'blur' }
            // {
            //   validator(rule, value, callback) {
            //     isPoneAvailable(value)
            //       ? callback(new Error('请输入正确的手机号'))
            //       : callback()
            //   },
            //   trigger: 'blur'
            // }
          ]
        },
        fields: [this.getColumn()]
      },
      isInfo: false
    }
  },
  created() {
    const vm = this
    // 平台列表
    platformList().then((data) => {
      vm.platformOptions = data
      vm.formItems[4].options = data
    })
    // 客户列表
    companyList().then((data) => {
      vm.optionsCompany = data
    })
  },
  methods: {
    // 拉去订单
    handleSubmitPull() {
      this.$refs['handleSubmitPull'].validate((valid) => {
        if (valid) {
          this.loadingPull = true
          this.$http
            .post(`shops/manualPull/${this.shopId}`, this.formDataPull)
            .then((response) => {
              if (response.code === 10000) {
                this.$message.success('同步成功')
                this.formVisiblePull = false
                this.loadingPull = false
              } else {
                this.loadingPull = false
                this.$message.error(response.message)
              }
            }).catch(() => {
              this.loadingPull = false
            })
        }
      })
    },
    handleCancelPull() {
      this.shopId = ''
      this.formDataPull.startTime = ''
      this.formVisiblePull = false
    },
    // 拉取订单
    manualPull(shopId) {
      this.shopId = shopId
      this.formVisiblePull = true
    },
    changePlatform(val) {
      if (Number(val) === 1) {
        if (this.title === '新增') {
          this.formFieldsData.platformOptionsData.marketplaceId = 'ATVPDKIKX0DER'
        }
      }
    },
    // 显示详情 弹窗
    showInfoDialog(row) {
      const vm = this
      vm.title = '详情'
      vm.isInfo = true
      vm.$http.get(`/shop/${row.id}`).then(res => {
        vm.formFieldsData.code = res.data.code // 店铺代码
        vm.formFieldsData.shop_name = res.data.shop_name // 店铺名称
        vm.formFieldsData.platform_id = res.data.platform_id // 归属平台
        vm.formFieldsData.type = res.data.type // 运营类型 1-自营 2-代储存
        vm.formFieldsData.company_id = res.data.company_id
        vm.formFieldsData.remarks = res.data.remarks // 备注
        for (const key in res.data.platform_parameters) {
          vm.formFieldsData.platformOptionsData[key] = res.data.platform_parameters[key]
        }
        vm.model.fields = res.data.senderList
      })
      vm.formVisible = true
    },
    // 显示绑定 dialog
    showBindWarehouseDialog(id) {
      const vm = this
      vm.$refs.warehouse.show(id)
    },
    // 显示 绑定 人员 dialog
    showBindUserDialog(id) {
      const vm = this
      vm.$refs.user.show(id)
    },
    // 更新input不能输入的问题
    inputChange() {
      this.$forceUpdate()
    },
    editOpen(index) {
      const vm = this
      const data = { ...this.model }
      data.fields[index].disabled = false
      vm.model = Object.assign({}, vm.model, {
        rules: data.rules,
        fields: data.fields
      })
    },
    // 新增之前
    beforeCreate() {
      this.formFieldsData.platformOptionsData = {}
      this.model.fields = []
      this.formFieldsData.platform_id = ''
      this.formFieldsData.company_id = ''
      this.formFieldsData.id = ''
      this.formFieldsData.platformOptionsData.marketplaceId = 'ATVPDKIKX0DER'
    },
    // 编辑详情
    handleUpdateNew(data) {
      this.title = '编辑'
      this.$http.get(`shop/${data.id}`).then((res) => {
        if (res.code === 10000) {
          const dataObj = res.data
          this.formFieldsData = dataObj
          this.formFieldsData.platformOptionsData = dataObj.platform_parameters
          this.model.fields = dataObj.userList.map((arr) => {
            arr.disabled = true
            return arr
          })
          this.formVisible = true
        }
      })
    },
    // 获取添加参数组合
    getData() {
      const data = Object.assign({}, this.formFieldsData)
      delete data.updated_at
      delete data.created_at
      //   data['is_status'] = 1
      data['platform_parameters'] = JSON.stringify(
        this.formFieldsData.platformOptionsData
      )
      if (this.model.fields && this.model.fields.length > 0) {
        data['sender_data'] = JSON.stringify(this.model.fields)
      }
      return data
    },
    list() {
      this.senderList()
    },
    // 寄件人信息列表
    senderList() {
      const vm = this
      const data = {
        limit: 100,
        page: 1,
        shop_id: this.formFieldsData.id
      }
      vm.$http
        .get('sender', {
          params: data
        })
        .then((res) => {
          if (res.code === 10000) {
            this.model.fields = res.data.map((arr) => {
              arr.disabled = true
              return arr
            })
          }
        })
    },
    // 数据列表
    getColumn() {
      return {
        warehouse_name: '',
        name: '',
        company: '',
        phone: '',
        mobile: '',
        street: '',
        city: '',
        city_code: '',
        post_code: '',
        is_default: 0,
        disabled: false
      }
    },
    // 提交信息
    handleSubmitNew() {
      this.$refs['shops'].validate((valid) => {
        if (valid) {
          // 编辑
          if (this.formFieldsData.id) {
            this.$http
              .put(`shop/${this.formFieldsData.id}`, this.getData())
              .then((response) => {
                if (response.code === 10000) {
                  this.$message.success('编辑成功')
                  this.formVisible = false
                  this.handleRefresh()
                } else {
                  this.$message.error(response.message)
                }
              })
          } else {
            // 添加
            this.$http.post('shop', this.getData()).then((response) => {
              if (response.code === 10000) {
                this.$message.success('添加成功')
                this.formVisible = false
                this.handleRefresh()
              } else {
                this.$message.error(response.message)
              }
            })
          }
        }
      })
    },
    // 客户模糊搜索
    remoteMethod(query) {
      if (query !== '') {
        this.loadingCompany = true
        companyList(query).then((data) => {
          setTimeout(() => {
            this.optionsCompany = data
            this.loadingCompany = false
          }, 200)
        })
      } else {
        this.optionsCompany = []
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.el-select .el-input {
  width: 130px;
}

.input-with-select .el-input-group__prepend {
  background-color: #fff;
}
</style>
